package cn.chowx.myjfinal.system;

import org.apache.commons.lang3.math.NumberUtils;

import com.google.common.base.Strings;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.chowx.myjfinal.common.BaseController;
import cn.chowx.myjfinal.help.PageHelp;
import cn.chowx.myjfinal.system.model.SysAction;
import cn.chowx.myjfinal.system.model.SysRole;
import cn.chowx.myjfinal.system.model.SysRoleAction;

/**
 * 角色 controller
 * @author zcqshine
 *
 */
public class SysRoleController extends BaseController {
	/**
	 * 跳转到角色列表页面
	 */
	public void index(){
		String roleKeyValue = SysRole.DAO.getSelectKeyValue();
		setAttr("roleKeyValue",roleKeyValue);
		render("role.html");
	}
	
	/**
	 * 获取角色列表,分页数据
	 */
	public void list(){
		super.setPageHelp();
		Page<Record> page = SysRole.DAO.findRecordList(pageHelp);
		renderJsonData(page);
	}
	
	/**
	 * 创建,更新,删除角色
	 */
	public void cud(){
		String oper = getPara("oper");
		
		int id = NumberUtils.toInt(getPara("id"));
		String roleName = getPara("roleName");
		int parentId = NumberUtils.toInt(getPara("parentId"));
		int status = NumberUtils.toInt(getPara("status"));
		String value = getPara("value");
		
		SysRole role = new SysRole();
		role.set("id",id);
		role.set("roleName",roleName);
		role.set("parentId",parentId);
		role.set("status",status);
		role.set("value",value);
		

		String msg = null;
		
		if(!Strings.isNullOrEmpty(oper)){
			switch (oper) {
			case PageHelp.OPER_CREATE:
				msg = save(role);
				break;
			case PageHelp.OPER_UPDATE: 
				msg = update(role);
				break;
			case PageHelp.OPER_DELETE:
				msg = delete(role);
				break;
			default:
				break;
			}
		}
		renderJson(msg);
	}
	
	/**
	 * 获取 Json 格式的资源列表
	 */
	public void getActions(){
		int roleId = NumberUtils.toInt(getPara("roleId"));
		if(roleId > 0){
			renderJson(SysAction.DAO.getActionJson(roleId));
		}else{
			renderJson("");
		}
	}
	
	/**
	 * 更新角色资源
	 */
	public void updateAction(){
		int roleId = NumberUtils.toInt(getPara("roleId"));
		String actIdAndChk = getPara("actIdAndChk");
		if(!Strings.isNullOrEmpty(actIdAndChk)){
			String[] keyValues = actIdAndChk.split(",");
			boolean flag = SysRoleAction.DAO.saveOrUpdate(roleId, keyValues);
			renderJson(flag?"":"操作失败");
		}else{
			renderJson("操作失败");
		}
		
	}
	
	private String save(SysRole role){
		boolean flag = role.save();
		if(flag){
			return "增加角色成功";
		}else{
			return "增加角色失败";
		}
	}
	
	private String update(SysRole role){
		boolean flag = role.update();
		if(flag){
			return "更新角色成功";
		}else{
			return "更新角色失败";
		}
	}
	
	private String delete(SysRole role){
		boolean flag = role.delete();
		if(flag){
			return "删除成功";
		}else{
			return "删除失败";
		}
	}
	
	
}
